import os

from django.conf              import settings
from django.template          import TemplateDoesNotExist
from django.template.loader   import BaseLoader
from django.utils._os         import safe_join
from sitepal.sitetheme.media  import TemplateMedium
from sitepal.sitetheme.models import Theme

class TemplateLoader(BaseLoader):
    is_usable = True

    def get_template_sources(self,template_name,template_dirs=None):
        if not template_dirs:
            template_dirs = settings.TEMPLATE_DIRS
        for template_dir in template_dirs:
            try:
                filename = safe_join(template_dir,template_name)
                if os.path.isfile(filename):
                    yield filename
            except UnicodeDecodeError:
                raise
            except ValueError:
                pass
        theme = Theme.objects.get_current()
        try:
            medium = theme.get_medium(template_name)
            if isinstance(medium,TemplateMedium):
                yield medium.filename
        except KeyError:
            pass

    def load_template_source(self,template_name,template_dirs=None):
        tried = []
        for filepath in self.get_template_sources(template_name,template_dirs):
            try:
                file = open(filepath)
                try:
                    return (file.read().decode(settings.FILE_CHARSET),filepath)
                finally:
                    file.close()
            except IOError:
                tried.append(filepath)
        if tried:
            error_msg = "Tried %s" % tried
        else:
            error_msg = "Your theme template dirs are empty."
        raise TemplateDoesNotExist(error_msg)
    load_template_source.is_usable = True

